import {EventEmitter, Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  private products: Array<Product> = [
    new Product(1, '第一个商品', 1.99, 3.5, '这是第一个商品，是我在学习慕课网Angular入门实战时创建的', ['电子产品', '硬件设备']),
    new Product(2, '第二个商品', 2.99, 2.5, '这是第二个商品，是我在学习慕课网Angular入门实战时创建的', ['图书']),
    new Product(3, '第三个商品', 3.99, 3.5, '这是第三个商品，是我在学习慕课网Angular入门实战时创建的', ['硬件设备']),
    new Product(4, '第四个商品', 4.99, 1.5, '这是第四个商品，是我在学习慕课网Angular入门实战时创建的', ['电子产品', '硬件设备']),
    new Product(5, '第五个商品', 5.99, 4.5, '这是第五个商品，是我在学习慕课网Angular入门实战时创建的', ['电子产品']),
    new Product(6, '第六个商品', 6.99, 2.5, '这是第六个商品，是我在学习慕课网Angular入门实战时创建的', ['图书']),
    new Product(7, '第七个商品', 6.99, 2.5, '这是第六个商品，是我在学习慕课网Angular入门实战时创建的', ['图书']),
  ];

  private comments: Comment[] = [
    new Comment(1, 1, '2017-02-02 22:22:22', '张三', 3, '东西不错'),
    new Comment(2, 1, '2018-02-02 22:22:22', '李四', 3, '东西一般'),
    new Comment(3, 1, '2019-02-02 22:22:22', '张无忌', 3, '比不上我的九阳神功'),
    new Comment(4, 2, '2019-03-02 22:22:22', '曾阿牛', 3, '比不上我的乾坤大挪移'),
  ];

  // 用来传输搜索模块的搜索参数对象的事件发射器
  searchEvent: EventEmitter<ProductSearchParams> = new EventEmitter();

  constructor(private http: HttpClient) {
  }

  // 获取所有商品
  getProducts(): Observable<any> {
    return this.http.get('/api/products');
  }

  // 根据id返回商品
  getProduct(id: number): Observable<any> {
    console.log(id);
    return this.http.get('/api/product/' + id);
  }

  // 根据商品id返回该商品的评论信息
  getCommentsForProductId(id: number): Observable<any> {
    return this.http.get('/api/product/' + id + '/comments');
  }

  // 返回所有分类
  getAllCategories(): string[] {
    return ['电子产品', '图书', '硬件设备'];
  }

  search(params: ProductSearchParams): Observable<any> {
    return this.http.get('/api/products', {params: this.encodeParams(params)});
  }

  encodeParams(params: ProductSearchParams): HttpParams {
    const a = Object.keys(params).filter(key => params[key])
      .reduce((sum: HttpParams, key: string) => {
        sum = sum.append(key, params[key]);
        return sum;
      }, new HttpParams());
    console.log(a.get('title'));
    console.log(a.get('price'));
    console.log(a.get('category'));
    return a;
  }
}

export class Product {
  constructor(
    public id: number,
    public title: string,
    public price: number,
    public rating: number,
    public desc: string,
    public categories: Array<string>
  ) {
  }
}

export class Comment {
  constructor(
    public id: number,
    public productId: number,
    public timestamp: string,
    public user: string,
    public rating: number,
    public content: string
  ) {
  }
}

export class ProductSearchParams {
  constructor(
    public title: string,
    public price: number,
    public category: string
  ) {
  }
}
